#!coding: utf-8
import cv2
import numpy as np
import os
import time
from picamera2 import Picamera2
import sys

try:
    picam = Picamera2(0)
except Exception as e:
    print(e)
    print('未检测到摄像头，确保开机之前接入，按退出键退出')
    sys.exit()
config = picam.create_still_configuration(main={'format': 'RGB888'})
picam.configure(config)
picam.start()

Key_Esc = 27
Key_Back = 191
Key_Ok = 13
cv2.namedWindow('frame', cv2.WINDOW_NORMAL)
cv2.setWindowProperty('frame', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)

# 创建保存目录
save_dir = "/home/pi/Lepi_Data/Photo"
os.makedirs(save_dir, exist_ok=True)

while True:
    # 逐帧捕获
    frame = picam.capture_array()
    resize = cv2.resize(frame, (320, 240))
    cv2.imshow('frame', np.rot90(resize, 3))
    # cv2.imshow('frame', np.rot90(cv2.resize(frame,(320,240))))
    # 按Esc键退出，不加这一句可能无法正常显示图像
    key = cv2.waitKey(1)
    if key > 0:
        print(key)
    if key == Key_Esc or key == Key_Back:
        break
    if key == Key_Ok:
        timestamp = time.strftime("%Y%m%d_%H%M%S")
        filename = f"photo_{timestamp}.jpg"
        filepath = os.path.join(save_dir, filename)
        cv2.imwrite(filepath, frame)
        print(f'图片已保存至{filepath}')
        os.system('aplay /home/pi/workspace/lepi-gui/app/static/apps/camera/shutter_sound.wav')
# 完成所有操作后，释放捕获器
picam.stop()
cv2.destroyAllWindows()
print('运行结束，按退出键退出')

